package com.minidb.utils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public final class Helpers {
    private Helpers() {}

    // 简单判断字符串是否为整数（不支持小数）
    public static boolean isNumeric(String s) {
        if (s == null || s.isEmpty()) return false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (i == 0 && (c == '+' || c == '-')) continue;
            if (!Character.isDigit(c)) return false;
        }
        return true;
    }

    // 从 SQL 文件中读取多条语句（按 ; 分割，去掉空行与 //、-- 注释）
    public static List<String> loadSQLFromFile(String filePath) throws IOException {
        String content = Files.readString(Path.of(filePath));
        StringBuilder sb = new StringBuilder();
        List<String> stmts = new ArrayList<>();
        String[] lines = content.split("\\R");

        for (String line : lines) {
            String trimmed = line.trim();
            if (trimmed.startsWith("--") || trimmed.startsWith("//") || trimmed.isEmpty()) continue;
            sb.append(trimmed).append(' ');
            if (trimmed.endsWith(";")) {
                String sql = sb.toString().trim();
                if (sql.endsWith(";")) sql = sql.substring(0, sql.length() - 1);
                if (!sql.isEmpty()) stmts.add(sql);
                sb.setLength(0);
            }
        }
        // 最后一条可能没有分号
        String rest = sb.toString().trim();
        if (!rest.isEmpty()) stmts.add(rest);
        return stmts;
    }
}
